from functools import partial

from django.core.exceptions import ObjectDoesNotExist
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import BasePermission
from rest_framework.request import Request

from user.models import User
from .token import userValidate

"""
-------------------------------
认证器部分
-------------------------------
"""


class isLogin(BaseAuthentication):
    def authenticate(self, request: Request):
        token: str = request.COOKIES.get('token', None)
        try:
            user = userValidate.check(token)
            print(user)
            request.user = user
        except ObjectDoesNotExist:
            print("【403】用户无法解析")
            return [None, None]
        return [user, None]


"""
-------------------------------
权限器部分
-------------------------------
"""


class hasUser(BasePermission):
    def has_permission(self, request: Request, view):
        """
        判断认证是否通过
        @param request:
        @param view:
        @return:q
        """
        if not request.user is not None:
            print("【403】用户无权限hasUser")
            raise PermissionDenied(detail="你没有登录。")

        return True


class adminMust(BasePermission):
    def has_permission(self, request: Request, view):
        """
        判断认证是否通过
        @param request:
        @param view:
        @return:q
        """
        user: User = request.user
        if not request.user.is_superuser:
            print("【403】用户无权限adminMust")
            print(user.username)
            print(user)
            raise PermissionDenied(detail="你不是Admin")
        return True


class OrPermission(BasePermission):
    def __init__(self, *perms):
        self.perms = perms

    def has_permission(self, request, view):
        last = None
        # 捕获PermissionDenied异常，继续检查其他权限
        for perm in self.perms:
            try:
                if perm().has_permission(request, view):
                    return True
            except PermissionDenied as e:
                last = e
                continue
        raise last


class publicSelect(BasePermission):
    """
    公开查询
    """

    def has_permission(self, request: Request, view):
        # print(request.method)
        return request.method == "GET"


"""
-------------------------------
权限工具部分
-------------------------------
"""


def orPermissionSet(*permissions):
    return partial(OrPermission, *permissions)
